package queue

import (
	"fmt"
	"github.com/spf13/viper"
	"reflect"
	"time"
)

var (
	jobChan chan Job
)

func Init() {
	jobChan = make(chan Job, 5000)
	startWorker()
}

// 入队
func EnQueue(job Job) {
	// enqueue a job
	jobChan <- job
}

// 等待job
func worker(jobChan <-chan Job) {
	index := 0
	for job := range jobChan {

		// 控制api请求速率
		if index != 0 && index%viper.GetInt("tai.maxQuerySec") == 0 {
			time.Sleep(time.Duration(1) * time.Second)
		}

		println(fmt.Sprintf("running job %s", reflect.TypeOf(job).Name()))
		err := job.Process()
		if err != nil {
			job.HandleError(err)
		}
		index++
	}
}

// 开启worker
func startWorker() chan Job {

	// start the worker
	go worker(jobChan)

	return jobChan
}
